package com.heoma.kafka.sample;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * 消息生产者
 */
public class ProducerQuickStart {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //kafka的连接配置信息
        Properties prop = new Properties();
        //连接地址
        prop.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.86.129:9092");
        //key的序列化
        prop.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        //value的序列化
        prop.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        //ack消息配置 消息确认机制
        prop.put(ProducerConfig.ACKS_CONFIG, "all");
        //重试次数
        prop.put(ProducerConfig.RETRIES_CONFIG, 10);
        //消息的压缩
        prop.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"snappy");
        //kafka生产者对象
        KafkaProducer<String, String> producer = new KafkaProducer<>(prop);
        /**
         * topic
         * 消息的key
         * 消息的value
         */
        ProducerRecord<String, String> KvProducerRecord = new ProducerRecord<>(
                "topic-frist",
                "100001",
                "hello"
        );
        //发送消息
        //同步发送消息
        /*RecordMetadata recordMetadata = producer.send(KvProducerRecord).get();
        long offset = recordMetadata.offset();
        System.out.println(offset);
        System.out.println("发送成功");*/
        //异步消息发送
        producer.send(KvProducerRecord, new Callback() {
            @Override
            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                if (e != null) {
                    System.out.println("记录异常信息");
                }
                System.out.println(recordMetadata.offset());
            }
        });
        //关闭消息通道
        producer.close();
    }
}
